package com.iwomy.secureplat.platform.listener;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.iwomy.secureplat.platform.constant.RedisConstants;
import com.iwomy.secureplat.platform.entity.*;
import com.iwomy.secureplat.platform.service.*;
import com.iwomy.secureplat.platform.transmission.parse.EmpaerDataParse;
import com.iwomy.secureplat.platform.transmission.entity.SensorTransmissionData;
import com.iwomy.secureplat.platform.utils.RedisClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

	protected final Logger logger = LoggerFactory.getLogger(this.getClass());


	public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
		super(listenerContainer);
	}


	@Resource
	private AlarmFaultLoggingService alarmFaultLoggingService;
	@Resource
	private BasicDeviceService basicDeviceService;
	@Resource
	BasicAlarmContactsService basicAlarmContactsService;
	@Resource
	BasicInstallLocationService basicInstallLocationService;
	@Resource
	AlarmEventTypeService alarmEventTypeService;
	@Resource
	private MongoTemplate mongoTemplate;
	@Resource
	BasicNotificationRecordService basicNotificationRecordService;
	@Resource
	RedisClient redisClient;


	/**
	 * 使用该方法监听，当我们key过期是自动调用该方法
	 *
	 * @param message
	 * @param pattern
	 */
	@Override
	public void onMessage(Message message, byte[] pattern) {
		//就是过期的key
		String key = message.toString();
		if (key.contains(RedisConstants.REDIS_KEY_DEVICE_ONLINE)) {
			//更新设备状态为离线
			String tid = key.replace(RedisConstants.REDIS_KEY_DEVICE_ONLINE, "");
			if(!redisClient.tryLock(RedisConstants.REDIS_KEY_DEVICE_ONLINE_LOCK+tid,tid)){
				logger.error("{}联网超时，未获取到锁", tid);
				return;
			}
			logger.info("{}联网超时", tid);

			BasicDeviceEntity basicDeviceEntity = basicDeviceService.getByImei(tid);
			basicDeviceEntity.setDeviceState(30);
			basicDeviceEntity.setOnline(10);
			basicDeviceEntity.setRecentEventTime(LocalDateTime.now());
			basicDeviceService.updateById(basicDeviceEntity);
			BasicInstallLocationEntity installLocation = basicInstallLocationService.getById(basicDeviceEntity.getInstallLocationId());
			BasicAlarmContactsEntity alarmContacts = basicAlarmContactsService.getById(installLocation.getAlarmWorkerId());

			//根据设备类型查询是什么协议

//			List<AlarmEventTypeEntity> timeout = alarmEventTypeService.listByBasicDeviceAndCode(basicDeviceEntity, "TIMEOUT", null, "empaer");
//			if (ObjectUtil.isEmpty(timeout)) return;
//			AlarmEventTypeEntity alarmEventTypeEntity = timeout.get(0);
			AlarmFaultLoggingEntity faultLogging = new AlarmFaultLoggingEntity();
			faultLogging.setDeptId(basicDeviceEntity.getDeptId());
			faultLogging.setTenantId(basicDeviceEntity.getTenantId());
			alarmFaultLoggingService.save(faultLogging);
			faultLogging.setAlarmCauses("最后一次联网时间：" + DateUtil.formatLocalDateTime(LocalDateTime.now().plusMinutes(-2)) + "；联网超时");
			faultLogging.setDeviceId(basicDeviceEntity.getId());
			faultLogging.setImei(basicDeviceEntity.getImei());
			faultLogging.setEventTypeName("联网超时");
			faultLogging.setDeviceTypeId(basicDeviceEntity.getDeviceTypeId());
			faultLogging.setDeviceTypeName(basicDeviceEntity.getDeviceTypeName());
			faultLogging.setDeviceModelId(basicDeviceEntity.getDeviceModelId());
			faultLogging.setDeviceModelName(basicDeviceEntity.getDeviceModelName());
			faultLogging.setInstallLocationId(basicDeviceEntity.getInstallLocationId());

			EmpaerDataParse empaerDataParse = new EmpaerDataParse();
			BasicNotificationRecordEntity sendSmsMsgNotificationRecord =
					empaerDataParse.sendSmsMsg(basicDeviceEntity, installLocation, alarmContacts, "联网超时");
			basicNotificationRecordService.save(sendSmsMsgNotificationRecord);
			faultLogging.setSmsAlarmId(sendSmsMsgNotificationRecord.getId());
			faultLogging
					.setSmsAlarmSketch(sendSmsMsgNotificationRecord.getSketch());


			BasicNotificationRecordEntity callPhoneNotificationRecord =
					empaerDataParse.callPhone(basicDeviceEntity, installLocation, alarmContacts, "联网超时");
			basicNotificationRecordService.save(callPhoneNotificationRecord);
			faultLogging.setTelephoneAlarmId(callPhoneNotificationRecord.getId());
			faultLogging
					.setTelephoneAlarmSketch(callPhoneNotificationRecord.getSketch());


			BasicNotificationRecordEntity officialAccountNotificationRecord =
					empaerDataParse.sendOfficialAccountMsg(basicDeviceEntity, installLocation, alarmContacts, "联网超时", faultLogging);
			basicNotificationRecordService.save(officialAccountNotificationRecord);
			faultLogging.setOfficialAccountAlarmId(officialAccountNotificationRecord.getId());
			faultLogging
					.setOfficialAccountAlarmSketch(officialAccountNotificationRecord.getSketch());

			alarmFaultLoggingService.updateById(faultLogging);
			SensorTransmissionData sensorTransmissionData = new SensorTransmissionData();
			sensorTransmissionData.setDeviceUniqueId(basicDeviceEntity.getImei());
			sensorTransmissionData.setReceptionTime(LocalDateTime.now());
			sensorTransmissionData.setAlarmEvenName("联网超时");
			sensorTransmissionData.setAlarmEvenCode("TIMEOUT");
			sensorTransmissionData.setAlarmInfo("TIMEOUT");
			sensorTransmissionData.setTenantId(basicDeviceEntity.getTenantId());
			sensorTransmissionData.setDeptId(basicDeviceEntity.getDeptId());
			sensorTransmissionData.setAlarmTypeCode("TIMEOUT");
			sensorTransmissionData.setAlarmTypeName("联网超时");
			sensorTransmissionData.setContent(faultLogging.getAlarmCauses());
//			sensorTransmissionData.setBatteryLevel("0");
//			sensorTransmissionData.setSignal("0");
			mongoTemplate.save(sensorTransmissionData);
			redisClient.del(RedisConstants.REDIS_KEY_DEVICE_ONLINE+tid);
			return;
		}

	}
}
